package com.ruoyi.web.controller.market.extend;

import cn.hutool.core.map.multi.AbsCollValueMap;
import cn.hutool.core.map.multi.SetValueMap;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.db.domain.*;
import com.ruoyi.db.mapper.MemberLoginsessionMapper;
import com.ruoyi.extend.service.IChannelInfoService;
import com.ruoyi.extend.service.ICountInfoService;
import com.ruoyi.db.model.vo.DataInfoVO;
import com.ruoyi.market.enums.SpecialEnum;
import com.ruoyi.member.service.IMemberExtInfoService;
import com.ruoyi.member.service.IMemberInfoService;
import com.ruoyi.member.service.IMemberLoginsessionService;
import com.ruoyi.product.service.IProductProfitAddupService;
import com.ruoyi.web.wapper.ProductProfitAddupWapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 渠道统计Controller
 * 
 * @author ruoyi
 * @date 2022-08-11
 */
@Controller
@RequestMapping("/extend/countview")
public class CountViewController extends BaseController
{
    private String prefix = "extend/count";

    @Autowired
    private ICountInfoService countInfoService;
    @Autowired
    private IMemberExtInfoService memberExtInfoService;
    @Autowired
    IChannelInfoService channelInfoService;
    @Autowired
    IProductProfitAddupService productProfitAddupService;
    @Autowired
    private IMemberLoginsessionService iMemberLoginsessionService;

    @GetMapping("channelInfoView/{countId}")
    public String count(ModelMap mmap,
                        @PathVariable("countId") String countId,
                        HttpServletRequest request)
    {
        mmap.put("countId", countId);
        mmap.put("ctx", ServerConfig.getDomain(request));
        return prefix + "/channelInfoView";
    }

    @GetMapping("uvCountView/{countId}")
    public String uvCountView(ModelMap mmap,
                        @PathVariable("countId") String countId,
                        HttpServletRequest request)
    {
        mmap.put("countId", countId);
        mmap.put("ctx", ServerConfig.getDomain(request));
        return prefix + "/uvCountView";
    }

    @GetMapping("proUvCountView/{countId}")
    public String proUvCountView(ModelMap mmap,
                              @PathVariable("countId") String countId,
                              HttpServletRequest request)
    {
        mmap.put("countId", countId);
        mmap.put("ctx", ServerConfig.getDomain(request));
        return prefix + "/proUvCountView";
    }

    @GetMapping("CountView/{countId}")
    public String CountView(ModelMap mmap,
                              @PathVariable("countId") String countId,
                              HttpServletRequest request)
    {
        mmap.put("countId", countId);
        mmap.put("ctx", ServerConfig.getDomain(request));
        return prefix + "/CountView";
    }


    @PostMapping("/proUvCountList")
    @ResponseBody
    public TableDataInfo proUvCountList(CountUvInfo countUvInfo)
    {

        CountInfo countInfo = countInfoService.selectCountInfoById(String.valueOf(countUvInfo.getCountId()));

        ProductProfitAddup productProfitAddup = new ProductProfitAddup();
        productProfitAddup.setReqChannelCode(countInfo.getChannelCode());
        productProfitAddup.setDateInfo(countInfo.getDateInfo());

        startPage();
        List<Map<String, Object>> mapList = productProfitAddupService.selectProUvCountListMap(productProfitAddup);
        return getDataTable(mapList);
    }

    @PostMapping("/CountList")
    @ResponseBody
    public TableDataInfo CountList(CountUvInfo countUvInfo)
    {
        CountInfo countInfo = countInfoService.selectCountInfoById(String.valueOf(countUvInfo.getCountId()));

        MemberLoginsession memberLoginsession = new MemberLoginsession();
        memberLoginsession.setReqChannelCode(countInfo.getChannelCode());
        memberLoginsession.setChannelName(countInfo.getChannelName());
        memberLoginsession.setDateInfo(countInfo.getDateInfo());

        List<Map<String, Object>> list = iMemberLoginsessionService.selectCountlist(memberLoginsession);
        return getDataTable(list);
    }

    /**
     * 删除渠道统计
     */
    @PostMapping( "/zhimaData/{countId}")
    @ResponseBody
    public AjaxResult zhimaData(@PathVariable("countId") String countId)
    {

        CountInfo countInfo = countInfoService.selectCountInfoById(countId);

        BigDecimal costAmount = BigDecimal.ZERO;

        ChannelInfo channelInfo = channelInfoService.selectChannelInfoByChannelCode(countInfo.getChannelCode());
        if (ObjectUtil.equal(channelInfo.getChargeType(), Integer.valueOf("1"))){
            costAmount = countInfo.getUvCost();
        }else{
            costAmount = countInfo.getRegisterCost();
        }

        List<DataInfoVO> dataInfoList = memberExtInfoService.getZhimaCountInfoByDateInfoAndChannelCode(countInfo.getDateInfo(), countInfo.getChannelCode());
        List<String> titleList = new ArrayList<>();
        BigDecimal finalCostAmount = costAmount;

        dataInfoList.stream().forEach(dataInfoVO -> {
            String nameByValue = SpecialEnum.ZhimaScore.getNameByValue(dataInfoVO.getLabel());
            // 计算每个的价格；
            BigDecimal reusltAmount = finalCostAmount.divide(new BigDecimal(dataInfoVO.getValue()), 1, RoundingMode.HALF_UP);
            String title = nameByValue + " | " + reusltAmount;
            dataInfoVO.setName(title);
            titleList.add(title);
        });

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dataList", dataInfoList);
        jsonObject.put("titleList", titleList);

        return success(jsonObject);
    }


    /**
     * 实人认证信息
     */
    @PostMapping( "/authData/{countId}")
    @ResponseBody
    public AjaxResult authData(@PathVariable("countId") String countId)
    {

        CountInfo countInfo = countInfoService.selectCountInfoById(countId);

        BigDecimal costAmount = BigDecimal.ZERO;

        ChannelInfo channelInfo = channelInfoService.selectChannelInfoByChannelCode(countInfo.getChannelCode());
        if (ObjectUtil.equal(channelInfo.getChargeType(), Integer.valueOf("1"))){
            costAmount = countInfo.getUvCost();
        }else{
            costAmount = countInfo.getRegisterCost();
        }

        List<DataInfoVO> dataInfoList = memberExtInfoService.getAuthCountInfoByDateInfoAndChannelCode(countInfo.getDateInfo(), countInfo.getChannelCode());
        List<String> titleList = new ArrayList<>();
        BigDecimal finalCostAmount = costAmount;

        dataInfoList.stream().forEach(dataInfoVO -> {

            String nameByValue = "未认证";
            if (ObjectUtil.equal(dataInfoVO.getLabel(), "1")){
                nameByValue = "已认证";
            }
            // 计算每个的价格；
            BigDecimal reusltAmount = finalCostAmount.divide(new BigDecimal(dataInfoVO.getValue()), 1, RoundingMode.HALF_UP);
            String title = nameByValue + " | " + reusltAmount;
            dataInfoVO.setName(title);
            titleList.add(title);
        });

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dataList", dataInfoList);
        jsonObject.put("titleList", titleList);

        return success(jsonObject);
    }


    /**
     * 年龄信息
     */
    @PostMapping( "/ageData/{countId}")
    @ResponseBody
    public AjaxResult ageData(@PathVariable("countId") String countId)
    {

        CountInfo countInfo = countInfoService.selectCountInfoById(countId);

        Map<String, List<Integer>> map = new HashMap<>();
        map.put("0-23", Arrays.asList(0, 23));
        map.put("24-55", Arrays.asList(23, 55));
        map.put("56-99", Arrays.asList(55, 99));

        List<String> titleList = new ArrayList<>();

        List<DataInfoVO> dataInfoList = new ArrayList<>();
        for (String key: map.keySet()){
            List<Integer> list = map.get(key);

            DataInfoVO dataInfoVo = memberExtInfoService.getAgeCountInfoByDateInfoAndChannelCode(countInfo.getDateInfo(), countInfo.getChannelCode(), list.get(0), list.get(1));

            String title = key+ " | " + dataInfoVo.getValue();

            dataInfoVo.setLabel(title);
            dataInfoVo.setName(title);
            dataInfoList.add(dataInfoVo);

            titleList.add(title);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dataList", dataInfoList);
        jsonObject.put("titleList", titleList);

        return success(jsonObject);
    }

    /**
     * 城市信息
     */
    @PostMapping( "/cityData/{countId}")
    @ResponseBody
    public AjaxResult cityData(@PathVariable("countId") String countId)
    {
        CountInfo countInfo = countInfoService.selectCountInfoById(countId);

        Long totalNumber = memberExtInfoService.getCountNumberByCountInfo(countInfo.getDateInfo(), countInfo.getChannelCode());

        List<Map<String, Object>> resultMapList = memberExtInfoService.getCityCountInfoByDateInfoAndChannelCode(countInfo.getDateInfo(), countInfo.getChannelCode());

        for (Map<String, Object> itemMap: resultMapList){
            Long number = (Long) itemMap.get("number");
            itemMap.put("rate", NumberUtil.div(number, totalNumber, 4).multiply(new BigDecimal(100)));
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dataList", resultMapList);
        jsonObject.put("totalNumber", totalNumber);

        return success(jsonObject);
    }

    /**
     * 城市信息
     */
    @PostMapping( "/registerZhima/{countId}")
    @ResponseBody
    public AjaxResult registerZhima(@PathVariable("countId") String countId)
    {
        CountInfo countInfo = countInfoService.selectCountInfoById(countId);

        List<Map<String, Object>> mapList = memberInfoService.getDataSortZhimaInfoByDateInfoAndChannelCode(countInfo.getDateInfo(), countInfo.getChannelCode());

        List<String> titleList = new ArrayList<>();
        List<DataInfoVO> dataInfoList = new ArrayList<>();

        for (Map<String, Object> map : mapList) {
            String zhima = (String)map.get("zhima");
            Long number = (Long)map.get("number");

            String nameByValue = SpecialEnum.ZhimaScore.getNameByValue(zhima);

            if (ObjectUtil.isNotEmpty(nameByValue)){

                nameByValue = nameByValue + " | "+ number;

                DataInfoVO dataInfoVO = new DataInfoVO();
                dataInfoVO.setValue(number.intValue());
                dataInfoVO.setLabel(nameByValue);
                dataInfoVO.setName(nameByValue);
                dataInfoList.add(dataInfoVO);

                titleList.add(nameByValue);
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dataList", dataInfoList);
        jsonObject.put("titleList", titleList);

        return success(jsonObject);
    }

    @Autowired
    IMemberInfoService memberInfoService;

}
